<template>
  <div class="order">
    <Form :shopInfo="shopInfo" :data-list="dataList" v-if="selected" @back="selected = false" ref="mealFormRef" />
    <Introduction :data-list="dataList" @selectMeal="selectMeal" v-else></Introduction>
  </div>
</template>

<script lang="ts">
import {
  Component,
  Ref,
  Vue
} from "vue-property-decorator";

import Introduction from "@/views/meal/Order/Introduction.vue";
import Form from "@/views/meal/Order/Form.vue";

import {
  getShopInfo
} from "@/api/businessCenter/setting";
import {
  getMealList
} from "@/api/meal/meal";

  @Component({
    components: {
      Introduction,
      Form,
    },
  })
export default class Index extends Vue {
    @Ref() readonly mealFormRef: HTMLFormElement;

    // 套餐列表
    dataList = [];

    // 店铺信息
    shopInfo = {};

    selected = false;

    created() {
      this.selected = false;
      this.getDataList();
      this.getInfo();
    }

    /**
     * 获取套餐列表
     */
    async getDataList() {
      try {
        const response = await getMealList();
        const {
          code,
          data
        } = response;
        if (code === 200) {
          this.dataList = data;
          this.dataList.forEach(meal => {
            if (meal.functionDesc && typeof meal.functionDesc === "string") {
              meal.functionDesc = meal.functionDesc.split(",");
            }
            if (meal.discountsJson && typeof meal.discountsJson === "string") {
              meal.discountsJson = JSON.parse(meal.discountsJson);
            }
          });
        } else {
          this.$message({
            type: "warning",
            message: "获取套餐信息失败！",
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    async getInfo() {
      try {
        this.shopInfo = await getShopInfo();
      } catch (e) {
        this.$message({
          type: "warning",
          message: e,
        });
      }
    }

    selectMeal(meal) {
      this.selected = true;
      this.$nextTick(() => {
        this.mealFormRef.selectMeal(meal);
      });
    }
}
</script>

<style lang="scss" scoped></style>